/**
 * 验证上传文件是不否非法
 * @param suffix 允许上传的集合,如果为空则使用默认允许集合
 * @param isInclude 是否包含在上传自添加的验证集合中
 * @returns {Boolean} 正确 true,非法 false
 */
function validateFile(suffix, isInclude) {
	if(!suffix || suffix.length == 0) {
		//只允许上传的文件类型
		suffix = new Array(".jpg", ".jpeg", ".png", ".xls", ".xlsx", ".docx", ".doc", ".bmp", ".ppt", ".pptx", ".pdf", ".swf", ".txt");
	}
	var valid = true;
	$("input[type='file']").each(function(i) {
		var val = this.value;
		if(val || val.length > 0) {
			var w = val.substring(val.lastIndexOf("."), val.length);
			if(!_validateFile(w, suffix, isInclude)) {
				mui.toast("不允许的文件类型 [*" + w + "]！");
				valid = false;
				return valid;
			}
		}
	});

	return valid;
}

/**
 * 文件类型验证
 * @param value 需要进行验证的后缀名
 * @param suffix 允许上传的集合,如果为空则使用默认允许集合
 * @param isInclude 是否包含在上传自添加的验证集合中
 * @returns {Boolean} 正确 true,非法 false
 */
function _validateFile(value, suffix, isInclude) {
	var valid = false;
	for(var i = 0; i < suffix.length; i++) {
		if(isInclude) {
			if(value.toLowerCase() == suffix[i]) {
				valid = true;
				break;
			}
		} else {
			if(value.indexOf(suffix[i]) != -1 || value.toUpperCase().indexOf(suffix[i]) != -1) {
				valid = true;
				break;
			}
		}
	}
	return valid;
}

/**
 * 文件重命名
 * @param {Object} oldName
 */
function getNewFileName(oldName,ext){
	var end = oldName.substring(oldName.lastIndexOf("."), oldName.length);
	var name = oldName.substring(0, oldName.lastIndexOf("."));
	var date = new Date();
	var newName = name+"_"+date.getTime()+end;
	if(ext) newName = ext+"_"+newName;
	return newName;
}

/**
 * 展示或下载
 * @param {Object} url
 * @param {Object} fileName
 * @param {Object} callBack
 */
function showOrDown(url,itemId,fileName,fileType,callBack) {
	if( !url || !itemId ) {
		mui.alert("抱歉暂时无法下载");
		return;
	}
	if(!fileName){//获取文件名
		fileName = localStorage.getItem(itemId);
		//防止重复下载
		if(!fileName
			|| fileName.substr(fileName.length - 3 , fileName.length)
				!= fileType  ){
			fileName = "_downloads/"+Math.floor(Math.random() * 100000000 + 10000000).toString() + '.' + fileType;
			localStorage.setItem(itemId,fileName);
		}
	}
	
	plus.io.resolveLocalFileSystemURL(fileName, function() {
		//alert("成功获取文件" + fileName);
		callBack(fileName);
	}, function() {
		//alert("获取文件失败开始下载" + fileName);
		mui.confirm("是否要下载该文件?",null,["下载","取消"],function(e){
			if(e.index == 0 ){
				mui.toast('开始下载文件...');
				downLoadMateris(url, fileName, function(path) {
					callBack ? callBack(plus.io.convertAbsoluteFileSystem( path )) : '';
				});
			}else{
				
			}
		},'div')
	});

}

/**
 * 根据 dispNameId 下载文件
 * @param {Object} regInfo id集合
 * @param {Object} dispNameId 文件编号
 */
function downLoadMateris(url, fileName, callBack) {
	createDownloadTask(url, fileName, function(path) {
		callBack ? callBack(path) : '';
	});
}

function openDir(path, callBack) {
	plus.runtime.openFile(path, {}, function(e) {
		plus.nativeUI.alert("无法打开此文件");
	});
}

//根据url name 下载
function createDownloadTask(url,name,callback) {
	var dtask = plus.downloader.createDownload(url, {filename:name}, function(d, status) {
		if(status == 200) {
			var path = plus.io.convertLocalFileSystemURL(d.filename);
//						console.log("~~~~~"+d.filename);
//						console.log("~~~~~"+path);
			localStorage.setItem(url, path);
			callback(path);
		} else {
		}
	});
	dtask.start();
}

/**
 * wangsh 20161123
 * 文件上传的方法
 * option jsomParam 
 */
function uploadFile(options) {
	if(!options) return;
	var url = utils.HOST+options.url;
	var filepath = options.filepath;
	var datas = options.datas || [];
	var success = options.success; //成功的回调
	var files = options.files;
	var fail = options.fail;
	var showWait = options.showWait?options.showWait:false;
	if(url) {
		var wt;
		if(showWait){
			wt=plus.nativeUI.showWaiting();
		}
		var task = plus.uploader.createUpload(url, {
				method: "POST",
				blocksize: 204800,
				priority: 100
			},
			function(t, status) {
				if(status == 200) {
					if(success) success(t);
				} else {
					if(fail) fail(status);
				}
				if(wt)wt.close();
			}
		);
		
		//单文件上传
		if(filepath)task.addFile(filepath, {key: 'file'});
		//多文件上传
		if(files && files.length>0){
			for(var i=0;i<files.length;i++){
				var f=files[i];
				task.addFile(f.path,{key:f.name});
			}
		}
		if(datas) {
			for(var key in datas){
				var _value = datas[key];
				if(_value){
					task.addData(key, _value);
				}
			}
		}
		task.start();
	}
};

/**
 * 删除材料 
 * @param {Object} path 材料路径
 */
function deleteFile(url,param,callBack){
	var param = jsonToParams(param)
	utils.ajax(url,function(data){
		console.log(data);
		data = JSON.parse(data);
		if(data.state == 1){
			callBack?callBack():'';
		}else{
			mui.toast("删除失败,请重试")
		}
	},param,{'showWait':true});
}

